//
//  CommunityMusicDetailsVC.swift
//  NDAi
//
//  Created by 丸子 on 2024/8/19.
//

import UIKit

class CommunityMusicDetailsVC: BaseViewController {
    let disposeBag = DisposeBag()
    let viewModel = CommunityViewModel()
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.navigationBar.isHidden = true
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        self.navigationController?.navigationBar.isHidden = false
    }
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
    }
    
    var model:CommunityModel? {
        didSet {
            playerView.setup(model: model)
        }
    }
    
   lazy  var playerView: HomeMusicPlayerView = {
       let view = HomeMusicPlayerView()
        return view
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.addSubview(playerView)

        playerView.historyBtn.setClosureTouchUpInside_k { [weak self] in
            let vc = MusicHistoryViewController()
            self?.navigationController?.pushViewController(vc)
        }
        
        playerView.backBtn.setClosureTouchUpInside_k { [weak self] in
            self?.navigationController?.popViewController(animated: true)
        }
        MusicPlayerManager.shared.dataSource = []
        
        if let model = self.model {
            var musicModel = MusicModel()
            musicModel.lyric_desc = model.music_lyric
            musicModel.create_time = model.create_time
            musicModel.style_text = model.style_text
            musicModel.share_page = model.share_page
            musicModel.title = model.title
            musicModel.music_url = model.play_url
            musicModel.sts = 2
            musicModel.cover_url = model.img_url
            musicModel.id = model.id
            musicModel.music_name = model.title
            musicModel.music_lyric = model.music_lyric
            MusicPlayerManager.shared.startPlayMusic(model: musicModel)
        }
           
        GlobalRx.updateMusicInfo.observe(on: MainScheduler.instance).subscribe(onNext: { [weak self] model in
            self?.playerView.setupMs(model: model)
        }).disposed(by: disposeBag)
        
        GlobalRx.playStateSubject.observe(on: MainScheduler.instance).subscribe(onNext: { [weak self] status in
             if status == .SUPlayerStatePlaying {
                  self?.playerView.playBtn.isSelected = true
//                  self?.playView.resumeRotation()
             }else {
                  self?.playerView.playBtn.isSelected = false
//                  self?.playView.pauseRotation()
             }
        }).disposed(by: disposeBag)
        
        GlobalRx.updateMusicProgress.observe(on: MainScheduler.instance).subscribe(onNext: { [weak self] currend, total, progress in
             self?.playerView.cuLb.text = currend
             self?.playerView.toLb.text = total
             self?.playerView.musicSlider.value = progress
        }).disposed(by: disposeBag)
        
        
        
        playerView.playBtn.setClosureTouchUpInside_k { [weak self] in
            if MusicPlayerManager.shared.playState == .SUPlayerStatePlaying {
                MusicPlayerManager.shared.pauseCurrentMusic()
            }else {
                MusicPlayerManager.shared.playCurrentMusic()
            }
        }
        
//        self.shareAudio(urlString: self.model?.share_page ?? "", viewController: self)

        
        playerView.rightBtn.setClosureTouchUpInside_k { [weak self] in
            guard let self = self else { return }
            self.shareLinkWithCover(urlString: self.model?.share_page ?? "", viewController: self)
//            self.navigationController?.popToRootViewController(animated: true)
        }
        
        playerView.likeBtn.setClosureTouchUpInside_k { [weak self] in
            if let model = self?.model {
                self?.viewModel.clickLike(model: model)
            }
        }
        
        playerView.saveBtn.setClosureTouchUpInside_k { [weak self] in
            guard let self = self else { return }
            self.shareAudio(urlString: self.model?.play_url ?? "", viewController: self)
        }
        
        
        self.viewModel.likeSubject.subscribe(onNext: { [weak self] type in
            guard let self = self else { return }
            if type == 1 {
                self.playerView.likeBtn.isSelected = true
                self.model?.like_count! += 1
            }else {
                self.playerView.likeBtn.isSelected = false
                self.model?.like_count! -= 1
            }
            self.model?.is_like = type
            playerView.setup(model: model)
        }).disposed(by: disposeBag)
       
    }
    
    func shareLinkWithCover(urlString: String, viewController: UIViewController) {
        guard let url = URL(string: urlString) else { return }

        // 创建一个包含链接和封面图片的数组
        let itemsToShare: [Any] = [url]
        
        // 创建分享活动视图控制器
        let activityViewController = UIActivityViewController(activityItems: itemsToShare, applicationActivities: nil)
        
        // 排除某些活动类型（根据需要）
        activityViewController.excludedActivityTypes = [
            .assignToContact,
            .saveToCameraRoll,
            .addToReadingList,
            .postToVimeo
        ]
        
        // 显示分享界面
        viewController.present(activityViewController, animated: true, completion: nil)
    }

    
    func shareAudio(urlString: String, viewController: UIViewController) {
        guard let url = URL(string: urlString) else { return }
        // 创建并显示加载指示器
        NDProgressHUD.showLoading()
        // 下载音频文件到本地
        let downloadTask = URLSession.shared.downloadTask(with: url) { (location, response, error) in
            DispatchQueue.main.async {
                // 隐藏加载指示器
                NDProgressHUD.hide()
            }
            guard let location = location, error == nil else {
                print("下载音频文件失败: \(error?.localizedDescription ?? "未知错误")")
                return
            }
            // 创建文件管理器
            let fileManager = FileManager.default
            // 将文件移动到临时目录
            let destinationURL = fileManager.temporaryDirectory.appendingPathComponent(response?.suggestedFilename ?? url.lastPathComponent)
            do {
                // 如果文件已经存在，删除它
                if fileManager.fileExists(atPath: destinationURL.path) {
                    try fileManager.removeItem(at: destinationURL)
                }
                // 移动下载的文件到目标路径
                try fileManager.moveItem(at: location, to: destinationURL)
                // 在主线程中展示分享界面
                DispatchQueue.main.async {
                    let activityViewController = UIActivityViewController(activityItems: [destinationURL], applicationActivities: nil)

                    // 排除某些活动类型（根据需要）
                    activityViewController.excludedActivityTypes = [
                        .assignToContact,
                        .saveToCameraRoll,
                        .addToReadingList,
                        .postToVimeo
                    ]

                    // 显示分享界面
                    viewController.present(activityViewController, animated: true, completion: nil)
                }
            } catch {
                print("移动音频文件失败: \(error.localizedDescription)")
            }
        }
        // 开始下载任务
        downloadTask.resume()
    }
    deinit {
        MusicPlayerManager.shared.removeCurrent()
    }
}

